package com.harvest.scientific.ladder.page

import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Matrix
import android.media.ExifInterface
import android.os.Bundle
import android.provider.MediaStore
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.harvest.scientific.ladder.R
import com.harvest.scientific.ladder.base.BaActivity
import com.harvest.scientific.ladder.databinding.ActInfo3Binding
import com.harvest.scientific.ladder.ext.asLifecycleOwner
import com.harvest.scientific.ladder.ext.dp2px
import com.harvest.scientific.ladder.ext.launchOnIO
import com.harvest.scientific.ladder.ext.launchOnMain
import com.harvest.scientific.ladder.ext.loadCorner
import com.harvest.scientific.ladder.ext.visible
import com.harvest.scientific.ladder.util.FlowBus
import com.harvest.scientific.ladder.util.FlowBusConstant
import com.harvest.scientific.ladder.util.ImageUtils
import com.harvest.scientific.ladder.util.LogUtils
import com.harvest.scientific.ladder.util.StbarUtil
import com.harvest.scientific.ladder.util.ToastUtil
import com.harvest.scientific.ladder.util.compress.ImageCompress
import com.harvest.scientific.ladder.util.compress.OnCompressListener
import java.io.File
import java.io.IOException
import java.util.Locale


class Info3Activity: BaActivity(), View.OnClickListener {

    private lateinit var binding: ActInfo3Binding

    private val CODE_REQUEST_PERMISSION_CARD_TAKE = 1000
    private val CODE_REQUEST_PERMISSION_FACE_TAKE = 2000
    private val CODE_REQUEST_PERMISSION_CARD_ALBUM = 3000
    private val CODE_REQUEST_PERMISSION_FACE_ALBUM = 4000
    private val TAG = "Info3Activity"

    private var hadSucUploadCard = false
    private var hadSucUploadFace = false

    private var takeCardPath = ""
    private var takeFacePath = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StbarUtil.setStatusBar(this,false, Color.TRANSPARENT,true)
        binding = ActInfo3Binding.inflate(layoutInflater)
        setContentView(binding.root)
        initEvent()
        initTextChangedListener()
        initObserver()
        initData()

    }

    private fun initTextChangedListener() {
        binding.etAccount.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextStatus()
            }
        })
    }

    private fun initObserver() {
//        FlowBus.with<Unit>(FlowBusConstant.CLOSE_INFO).register(this) {
//            finish()
//        }
        appModel.showLoading.observe(asLifecycleOwner) {
            if (it) showLoading() else dismissLoading()
        }
        appModel.delayViolentTheirSuc.observe(asLifecycleOwner) {
            dismissLoading()
            if (it.first) {
                if (it.second == "00") {
                    hadSucUploadCard = true
                    binding.ivCard.loadCorner(takeCardPath, dp2px(8f).toInt(), R.mipmap.ic_card_demo,true)
                } else if (it.second == "02") {
                    hadSucUploadFace = true
                    binding.ivFace.loadCorner(takeFacePath, dp2px(8f).toInt(), R.mipmap.ic_card_face,true)
                }
            } else {
                ToastUtil.showToast(it.second)
            }
            checkNextStatus()
        }
        appModel.admireMoreAcheRes.observe(asLifecycleOwner) {
            if (it == null) {
                LogUtils.d(TAG,"admireMoreAcheRes is null")
            } else {
                if (it.absentRussianMedicineSound == "1") {
                    hadSucUploadCard = true
                }
                if (it.broadMidnightDessertGlasshouse == "1") {
                    hadSucUploadFace = true
                }
            }
            binding.ivCard.loadCorner(
                it?.peacefulShopkeeperGiftedEntireTomorrow,
                dp2px(8f).toInt(),
                R.mipmap.ic_card_demo,
                true
            )
            binding.ivFace.loadCorner(
                it?.spokenHeadacheScientificDarknessEveryBottom,
                dp2px(8f).toInt(),
                R.mipmap.ic_card_face,
                true
            )
            checkNextStatus()
        }
        appModel.saveInfo3Suc.observe(asLifecycleOwner) {
            dismissLoading()
            if (it) {
                startActivity(Intent(this@Info3Activity, Info4Activity::class.java))
            }
        }
        appModel.searchInfo3.observe(asLifecycleOwner) {
            if (!it?.terminalNeckHomelandPartner.isNullOrEmpty()) {
                binding.etAccount.setText(it?.terminalNeckHomelandPartner ?: "")
            }
            checkNextStatus()
        }
    }

    private fun initData() {
        appModel.admireMoreAche("4")
        appModel.fleeSocialistExpedition(4)
    }

    private fun initEvent() {
        binding.llBack.setOnClickListener(this)
        binding.tvNext.setOnClickListener(this)
        binding.ivCard.setOnClickListener(this)
        binding.ivFace.setOnClickListener(this)
        binding.tvExample.setOnClickListener(this)
        binding.tvProtocol.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        when(v) {
            binding.llBack -> {
                onBackPressed()
            }
            binding.tvNext -> {
                if (!hadSucUploadFace || !hadSucUploadCard) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                if (binding.etAccount.text.toString().trim().isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                showLoading()
                appModel.realiseArabPrescription3(4,binding.etAccount.text.toString().trim())
            }
            binding.ivCard -> {
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.setType("image/*");
                startActivityForResult(intent, CODE_REQUEST_PERMISSION_CARD_ALBUM)

//                PictureSelDialog(this@Info3Activity)
//                    .setAlbumClick {
//                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
//                            if (checkPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
//                                val intent = Intent(Intent.ACTION_GET_CONTENT)
//                                intent.setType("image/*");
//                                startActivityForResult(intent, CODE_REQUEST_PERMISSION_CARD_ALBUM)
//                            } else {
//                                ActivityCompat.requestPermissions(this@Info3Activity, arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE), CODE_REQUEST_PERMISSION_CARD_ALBUM)
//                            }
//                        } else {
//                            if (checkPermission(android.Manifest.permission.READ_MEDIA_IMAGES)) {
//                                val intent = Intent(Intent.ACTION_GET_CONTENT)
//                                intent.setType("image/*");
//                                startActivityForResult(intent, CODE_REQUEST_PERMISSION_CARD_ALBUM)
//                            } else {
//                                ActivityCompat.requestPermissions(this@Info3Activity, arrayOf(android.Manifest.permission.READ_MEDIA_IMAGES,android.Manifest.permission.READ_MEDIA_VIDEO), CODE_REQUEST_PERMISSION_CARD_ALBUM)
//                            }
//                        }
//                    }
//                    .setTakeClick {
//                        if (checkPermission(android.Manifest.permission.CAMERA)) {
//                            startActivityForResult(Intent(this@Info3Activity, InfoCardActivity::class.java),CODE_REQUEST_PERMISSION_CARD_TAKE)
//                        } else {
//                            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.CAMERA), CODE_REQUEST_PERMISSION_CARD_TAKE);
//                        }
//                    }.show()

            }
            binding.ivFace -> {
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.setType("image/*");
                startActivityForResult(intent, CODE_REQUEST_PERMISSION_FACE_ALBUM)
//                PictureSelDialog(this@Info3Activity)
//                    .setAlbumClick {
//                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
//                            if (checkPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
//                                val intent = Intent(Intent.ACTION_GET_CONTENT)
//                                intent.setType("image/*");
//                                startActivityForResult(intent, CODE_REQUEST_PERMISSION_FACE_ALBUM)
//                            } else {
//                                ActivityCompat.requestPermissions(this@Info3Activity, arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE), CODE_REQUEST_PERMISSION_FACE_ALBUM)
//                            }
//                        } else {
//                            if (checkPermission(android.Manifest.permission.READ_MEDIA_IMAGES)) {
//                                val intent = Intent(Intent.ACTION_GET_CONTENT)
//                                intent.setType("image/*");
//                                startActivityForResult(intent, CODE_REQUEST_PERMISSION_FACE_ALBUM)
//                            } else {
//                                ActivityCompat.requestPermissions(this@Info3Activity, arrayOf(android.Manifest.permission.READ_MEDIA_IMAGES,android.Manifest.permission.READ_MEDIA_VIDEO), CODE_REQUEST_PERMISSION_FACE_ALBUM);
//                            }
//                        }
//                    }
//                    .setTakeClick {
//                        if (checkPermission(android.Manifest.permission.CAMERA)) {
//                            startActivityForResult(Intent(this@Info3Activity, InfoCardActivity::class.java),CODE_REQUEST_PERMISSION_FACE_TAKE)
//                        } else {
//                            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.CAMERA), CODE_REQUEST_PERMISSION_FACE_TAKE);
//                        }
//                    }.show()

            }
            binding.tvExample -> {
                if (binding.ivExample.isVisible) {
                    binding.ivExample.visible(false)
                } else {
                    binding.ivExample.visible(true)
                }
            }
            binding.tvProtocol -> {
                WebViewActivity.jumProtocol(this@Info3Activity)
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (requestCode == CODE_REQUEST_PERMISSION_CARD_TAKE) {
                startActivityForResult(Intent(this@Info3Activity, InfoCardActivity::class.java),CODE_REQUEST_PERMISSION_CARD_TAKE)
            } else if (requestCode == CODE_REQUEST_PERMISSION_FACE_TAKE) {
                startActivityForResult(Intent(this@Info3Activity, InfoCardActivity::class.java),CODE_REQUEST_PERMISSION_FACE_TAKE)
            } else if (requestCode == CODE_REQUEST_PERMISSION_CARD_ALBUM) {
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.setType("image/*");
                startActivityForResult(intent, CODE_REQUEST_PERMISSION_CARD_ALBUM)
            } else if (requestCode == CODE_REQUEST_PERMISSION_FACE_ALBUM) {
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.setType("image/*");
                startActivityForResult(intent, CODE_REQUEST_PERMISSION_FACE_ALBUM)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if (resultCode == RESULT_OK) {
            if (requestCode == CODE_REQUEST_PERMISSION_CARD_TAKE || requestCode == CODE_REQUEST_PERMISSION_FACE_TAKE) {
                showLoading()
                val takePath = data.getStringExtra("path") ?: ""
                if (takePath.isEmpty()) {
                    ToastUtil.showToast(getString(R.string.info3_11))
                    return
                }
                val orientation: Int = getImageOrientation(takePath)
                var bitmap = BitmapFactory.decodeFile(takePath)
                if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                    bitmap = adjustPhotoRotation(bitmap, 90)
                } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270){
                    bitmap = adjustPhotoRotation(bitmap, 270)
                }
                val savePath = applicationContext.cacheDir.absolutePath+"${System.currentTimeMillis()}-save.png"
                launchOnIO {
                    if (ImageUtils.save(bitmap, savePath, Bitmap.CompressFormat.PNG)) {
                        if (requestCode == CODE_REQUEST_PERMISSION_CARD_TAKE) {
                            takeCardPath = savePath
                        } else {
                            takeFacePath = savePath
                        }
                        LogUtils.d(TAG, "savePath:$savePath")
                        launchOnIO {
                            ImageCompress.with(this@Info3Activity)
                                .load(savePath)
                                .ignoreBy(50)
                                .setTargetDir(ImageUtils.getPath())
                                .filter { path ->
                                    !(TextUtils.isEmpty(path) || path.lowercase(
                                        Locale.getDefault()
                                    ).endsWith(".gif"))
                                }
                                .setCompressListener(object : OnCompressListener {
                                    override fun onStart() {
                                    }

                                    override fun onSuccess(file: File) {
                                        LogUtils.d(TAG,"saveSuc compress path:${file.path} length:${file.length()}")
                                        if (requestCode == CODE_REQUEST_PERMISSION_CARD_TAKE) {
                                            appModel.delayViolentTheir("00",file)
                                        } else {
                                            appModel.delayViolentTheir("02",file)
                                        }
                                    }

                                    override fun onError(e: Throwable) {
                                        launchOnMain {
                                            dismissLoading()
                                            ToastUtil.showToast(getString(R.string.info3_11))
                                        }
                                    }
                                }).launch()
                        }
                    }
                }
            } else if (requestCode == CODE_REQUEST_PERMISSION_CARD_ALBUM || requestCode == CODE_REQUEST_PERMISSION_FACE_ALBUM) {
//                data.data?.let {
//                    val file = ImageUtils.uriToFile(this@Info3Activity, it)
//                    Glide.with(this@Info3Activity).load(file).into(binding.ivFace)
//                }


                data.data?.let {
//                    val uriToPath = ImageUtils.pickedUriToPath(this@Info3Activity, data.data!!) ?: ""
//                    if (uriToPath.isEmpty()) {
//                        ToastUtil.showToast(getString(R.string.info3_11))
//                        return
//                    }
                    showLoading()
                    val file = ImageUtils.ufkjdkekdj(this@Info3Activity, it)
                    if (file == null) {
                        ToastUtil.showToast(getString(R.string.info3_11))
                        return
                    }
                    val uriToPath = file.path
                    if (requestCode == CODE_REQUEST_PERMISSION_CARD_ALBUM) {
                        takeCardPath = uriToPath
                    } else {
                        takeFacePath = uriToPath
                    }
                    launchOnIO {
                        ImageCompress.with(this@Info3Activity)
                            .load(uriToPath)
                            .ignoreBy(50)
                            .setTargetDir(ImageUtils.getPath())
                            .filter { path ->
                                !(TextUtils.isEmpty(path) || path.lowercase(
                                    Locale.getDefault()
                                ).endsWith(".gif"))
                            }
                            .setCompressListener(object : OnCompressListener {
                                override fun onStart() {
                                }

                                override fun onSuccess(file: File) {
                                    LogUtils.d(TAG,"saveSuc compress path:${file.path} length:${file.length()}")
                                    if (requestCode == CODE_REQUEST_PERMISSION_CARD_ALBUM) {
                                        appModel.delayViolentTheir("00",file)
                                    } else {
                                        appModel.delayViolentTheir("02",file)
                                    }
                                }
                                override fun onError(e: Throwable) {
                                    launchOnMain {
                                        dismissLoading()
                                        ToastUtil.showToast(getString(R.string.info3_11))
                                    }
                                }
                            }).launch()
                    }
                }
            }
        }
    }

    private fun checkPermission(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(
            this@Info3Activity,
            permission
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun checkNextStatus() {
        if (getNextStatus()) {
            binding.tvNext.setBackgroundResource(R.drawable.bg_comon_sure_26)
        } else {
            binding.tvNext.setBackgroundResource(R.drawable.bg_comon_disable_sure_26)
        }
    }

    private fun getNextStatus(): Boolean {
        if (!hadSucUploadCard || !hadSucUploadFace || binding.etAccount.text.toString().trim().isNullOrEmpty()) {
            return false
        }
        return true
    }

    private fun adjustPhotoRotation(bitmap: Bitmap, orientationDegree: Int): Bitmap? {
        val matrix = Matrix()
        matrix.setRotate(orientationDegree.toFloat())
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    }

    private fun getImageOrientation(path: String?): Int {
        return try {
            val exifInterface = ExifInterface(path!!)
            exifInterface.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL
            )
        } catch (e: IOException) {
            ExifInterface.ORIENTATION_NORMAL
        }
    }

}